package edu.sctu.wangxiaoqiang.day20150628;

import java.io.*;

/**
 * Created by user25 on 2015/6/28.
 */
public class Serializable {

    /**
     * 序列化
     * @param obj
     * @param filename
     */
    public void WriteObject(Object obj,String filename){
        try {
            FileOutputStream fos = new FileOutputStream(filename);
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(obj);
            oos.flush();
            oos.close();
            fos.flush();
            fos.close();
            System.out.println("序列化成功");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 反序列化
     * @param filename
     * @return
     */
    public  Object readObject(String filename) {
        try{
            FileInputStream fis = new FileInputStream(filename);
            ObjectInputStream is = new ObjectInputStream(fis);
            Object temp = is.readObject();
            fis.close();
            is.close();
            if (temp != null){
                System.out.println("反序列化成功。");
                 return temp;
            }
        }
        catch(Exception ex){
            ex.printStackTrace();
        }
        return null;
    }
}
